<template>
  <div
    class="constellation-main"
  >
    <div class="charts-body">
      <el-row style="height: 100%">
        <el-col :span="4" class="show-table">
          <el-table :data="tableData" border style="width: 100%">
            <el-table-column prop="num" label="#" width="50" />
            <el-table-column prop="rate" label="频率" />
            <el-table-column prop="amplitude" label="幅度" />
          </el-table>
        </el-col>
        <el-col :span="20">
          <div id="harmonic" />
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
  import AnalyseHeader from '../header'
  import useChartsStore from '@/store/modules/charts'
  import Highcharts from '@/plugins/highcharts'
  // import harmonicOptions from '@/constant/harmonic'
  import useChartOptions from '@/common/hooks/chartOptions'
  // import themeStyle from '@/constant/theme'
  import Interval from '@/common/classes/interval'
  import useHarmonicForm from '@/store/modules/form/harmonicForm'
  import { numToPlot } from '@/utils/utils'
  import { round, cloneDeep } from 'lodash'

  defineComponent([AnalyseHeader])
  let instance = null
  let interval = null
  let renderers = []
  const params = useHarmonicForm()
  const { chartOptions, themeStyle } = useChartOptions('harmonic')
  const map = ref([])
  const TOTAL_RATE = 6 * 1e9
  const tableData = computed(() => {
    const center = params.centerFreqIn
    return new Array(10).fill(1).map((v, k) => ({
      num: k + 1,
      rate: partNum.value > k ? numToPlot(center * (k + 1)) : '',
      amplitude: generateAmplitude(k)
    }))
  })
  const harmonicOptions = ref(chartOptions.value)
  const chartsStore = useChartsStore()
  const chartData = ref([])
  const generateAmplitude = k => {
    if (!map.value[k]) {
      return ''
    }
    return round(Math.max(...map.value[k]), 2) + 'dbm'
  }
  const generateShape = (num = 5) => {
    renderers.forEach(r => r.destroy())
    renderers = []
    const { plotLeft, plotTop, plotSizeX, plotSizeY } = instance
    const path = [] // 添加路径
    for (let i = 1; i < num + 1; i++) {
      const x1 = (plotSizeX / num) * i + plotLeft - 0.5
      if (i < num) {
        path.push('M', x1, plotTop)
        path.push('L', x1, plotTop + plotSizeY)
      }
      const x2 = x1 - plotSizeX / (num * 2) - 5
      const y2 = plotSizeY + plotTop + 16
      const renderer = instance.renderer
        .text(i, x2, y2)
        .attr({
          zIndex: 10,
          fill: themeStyle.value.labelColor,
          color: '#fff',
          backgroundColor: '#fff'
        })
        .add()
        renderers.push(renderer)
    }
    // path.push('Z') // 关闭路径  // 将路径添加到图表中
    const renderer = instance.renderer.path(path).attr({ stroke: themeStyle.value.labelColor, 'stroke-width': 1.5 }).add()
    renderers.push(renderer)
  }
  // 有几块图表数据
  const partNum = computed(() => {
    const { num } = params
    const parts = Math.floor(TOTAL_RATE / chartsStore.file.centerFreqIn)
    if (parts > num) {
      return num
    }
    return parts
  })
  // 总共多少个点
  const totalPointsInView = computed(() => {
    return partNum.value * params.span / 1000
  })
  // 请求图表数据
  const requestChartsData = async () => {
    const { data } = await chartsStore.querySequence()
    chartData.value = data.iQpwr
  }
  const init = async () => {
    await requestChartsData()
    harmonicOptions.value.xAxis.max = totalPointsInView.value
    instance = new Highcharts.Chart('harmonic', harmonicOptions.value)
    generateShape(params.num)
    instance.redrawCb = () => generateShape(params.num)
    createInterval()
  }
  const createInterval = () => {
    interval = Interval.create(
      updateChartData,
      totalPointsInView.value,
      totalPointsInView.value,
      chartData.value.length
    )
  }
  const updateChartData = (start = 0) => {
    const result = []
    const pointNum = params.span / 1000
    for (let i = 0; i < partNum.value; i++) {
      const temp = []
      for (let j = 0; j < pointNum; j++) {
        const item = chartData.value[i * pointNum + j + start]
        result.push([i * pointNum + j, item])
        temp.push(item)
      }
      map.value[i] = temp
    }
    instance.series.forEach(s => {
      s.setData(result, true, false, false)
    })
  }

  watchEffect(() => {
    if (!chartOptions.value || !instance) {
      return
    }
    harmonicOptions.value = chartOptions.value
    harmonicOptions.value.xAxis.max = totalPointsInView.value
    instance.update(harmonicOptions.value, true)
    generateShape(params.num)
  })
  onMounted(() => {
    init()
  })
  onBeforeMount(() => {
    // 将本地缓存写入store
    chartsStore.readStorage()
    if (!chartsStore.getFileInfo().fileName) {
      router.push({ path: 'filemanage' })
    }
  })

  onBeforeUnmount(() => {
    // 将store里面的内容写入本地缓存
    chartsStore.writeStorage()
  })
  onUnmounted(() => {
    Interval.remove(interval)
  })
</script>

<style scoped lang="scss">
  .constellation-main {
    height: 100%;
    display: flex;
    flex-direction: column;
    .charts-body {
      flex: 1;
      .show-table {
        height: 100%;
        border-right: 1px solid grey;
      }
    }
  }
</style>
